package openglsuperbible.Chapter5;

import de.matthiasmann.twl.utils.PNGDecoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import openglsuperbible.glutils.*;
import openglsuperbible.glutils.Math3D;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL30.*;

/**
 *
 * @author Matthew
 */
public class Pyramid {
        public static final int DISPLAY_HEIGHT = 600;
        public static final int DISPLAY_WIDTH = 800;

        public long lastFrame;       
        private GLShader shaderTEXTURE_POINT_LIGHT_DIFF;
 
        private MatrixStack modelViewMatrix;  // Modelview Matrix
        private MatrixStack projectionMatrix; // Projection Matrix
        private GLFrustrum frustrum;    // View Frustum
        private GeometryTransform transformPipeline; // Geometry Transform Pipeline
        private GLFrame cameraFrame;
        GLFrame mObjectFrame; 
        private GLBatch pyramidBatch;
        private int textureID;

        public void initGL()
        {
            // Black background
            glClearColor(0.7f, 0.7f, 0.7f, 1.0f );
            shaderTEXTURE_POINT_LIGHT_DIFF = GLShaderFactory.getTexturePointLightDiffuseShader();
            glEnable(GL_DEPTH_TEST);
	    glEnable(GL_TEXTURE_2D); 
            frustrum = new GLFrustrum();               
            modelViewMatrix = new MatrixStack();
            cameraFrame = new GLFrame();           
            textureID = loadTexture("stone3",GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE);
            pyramidBatch = makePyramid(); 
        }
        
              
        
       GLBatch makePyramid()
       {            
            float dim = 1.0f;
            float[]  vApex = { 0.0f, dim, 0.0f };
            float[]  vFrontLeft = { -dim, -dim, dim };
            float[]  vFrontRight = { dim, -dim, dim };
            float[]  vBackLeft = { -dim, -dim, -dim };
            float[]  vBackRight = { dim, -dim, -dim };
            
            float[] norm1 =    { 0.0f, -1.0f, 0.0f};
            float[] norm2 =  Math3D.findNormal( vApex, vFrontLeft, vFrontRight);
            float[] norm3 =  Math3D.findNormal(vApex, vBackLeft, vFrontLeft);
            float[] norm4 =  Math3D.findNormal(vApex, vFrontRight, vBackRight);
            float[] norm5 =  Math3D.findNormal(vApex, vBackRight, vBackLeft);

            
            GLBatchFactory batch = new GLBatchFactory();
            
            batch.addVertex(vBackLeft,  norm1 ,new float[]{0.0f, 0.0f} );//float[] vertex, float[] normal, float[] texCoords
            batch.addVertex(vBackRight, norm1 ,new float[]{1.0f, 0.0f} );
            batch.addVertex(vFrontRight,norm1 ,new float[]{1.0f, 1.0f} );
            batch.addVertex(vFrontLeft, norm1 ,new float[]{0.0f, 1.0f} );
            batch.addVertex(vBackLeft,  norm1 ,new float[]{0.0f, 0.0f} );
            batch.addVertex(vFrontRight,norm1 ,new float[]{1.0f, 1.0f} );
            
            batch.addVertex(vApex,      norm2 ,new float[]{0.5f, 1.0f} );
            batch.addVertex(vFrontLeft, norm2 ,new float[]{0.0f, 0.0f} );
            batch.addVertex(vFrontRight,norm2 ,new float[]{1.0f, 0.0f} );
            
            batch.addVertex(vApex,      norm3 ,new float[]{0.5f, 1.0f} );
            batch.addVertex(vBackLeft,  norm3 ,new float[]{0.0f, 0.0f} );
            batch.addVertex(vFrontLeft, norm3 ,new float[]{1.0f, 0.0f} );
            
            batch.addVertex(vApex,      norm4 ,new float[]{0.5f, 1.0f} );
            batch.addVertex(vFrontRight,norm4 ,new float[]{0.0f, 0.0f} );
            batch.addVertex(vBackRight, norm4 ,new float[]{1.0f, 0.0f} );
            
            batch.addVertex(vApex,      norm5 ,new float[]{0.5f, 1.0f} );
            batch.addVertex(vBackRight, norm5 ,new float[]{0.0f, 0.0f} );
            batch.addVertex(vBackLeft,  norm5 ,new float[]{1.0f, 0.0f} );
 
            return batch.buildBatch();  
	}

 
        
       
    float angle = 0.0f;
        
    void render()
    {    
         angle+= 0.05f * getDelta();
         float vLightPos [] = { 1.0f, 1.0f, 0.0f };
         float vWhite [] = { 1.0f, 1.0f, 1.0f, 1.0f }; 

	 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

         modelViewMatrix.push();
         float[] mCamera = cameraFrame.getCameraMatrix();
         modelViewMatrix.multiply4(mCamera);  
         
         modelViewMatrix.translate(0, 0, -4.5f);
         modelViewMatrix.rotate(angle, 0.0f, 1.0f, 0.0f);    
              
         shaderTEXTURE_POINT_LIGHT_DIFF.useShader();        
        glBindTexture(GL_TEXTURE_2D, textureID);
        shaderTEXTURE_POINT_LIGHT_DIFF.setUniformMatrix4("mvMatrix", false, transformPipeline.getModelViewMatrix());
        shaderTEXTURE_POINT_LIGHT_DIFF.setUniformMatrix4("pMatrix", false, transformPipeline.getProjectionMatrix());
        shaderTEXTURE_POINT_LIGHT_DIFF.setUniform3("vLightPos",vLightPos);
        shaderTEXTURE_POINT_LIGHT_DIFF.setUniform4("vColor", vWhite);
        shaderTEXTURE_POINT_LIGHT_DIFF.setUniform1i("textureUnit0",0);  
        pyramidBatch.draw(shaderTEXTURE_POINT_LIGHT_DIFF.getAttributeLocations());
        
        
        modelViewMatrix.pop();

	Display.update();  
    }
        
       public void create() throws LWJGLException { 
            //Display    
            Display.setDisplayModeAndFullscreen(new DisplayMode(DISPLAY_WIDTH,DISPLAY_HEIGHT)); 
            
            Display.setTitle("Pyramid");
            Display.create();
            
            //Keyboard         
            Keyboard.create();   
            //Mouse          
            Mouse.setGrabbed(false);
            Mouse.create();  
            //OpenGL      
            initGL();    
            resizeGL();  
        }  
       
        public void resizeGL() {   
            glViewport(0,0,DISPLAY_WIDTH ,DISPLAY_HEIGHT);
            frustrum.setPerspective(70f, Display.getWidth()/ Display.getHeight(),1.0f, 100.0f);
            projectionMatrix = new MatrixStack(frustrum.getProjectionMatrix());
            // Set the transformation pipeline to use the two matrix stacks 
            transformPipeline = new GeometryTransform(modelViewMatrix, projectionMatrix);
        } 
       
            public void destroy() {  
                //Methods already check if created before destroying.  
                Mouse.destroy();   
                Keyboard.destroy();
                Display.destroy();     
            } 
        
            public static void main(String[] args) {
            Pyramid main = null;
            try { 
                 main = new Pyramid(); 
                main.create(); 
                main.run();
            }          
            catch(Exception ex) {  
                 
            }          
            finally { 
                if(main != null) {  
                    main.destroy();
                }         
            }      
        } 
            
            public void run() 
            {
                while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {              
                       
                render();
       
             
                Display.sync(60);
                Display.setVSyncEnabled(true); 
                
                }
            }
                        
                            	/** 
	 * Calculate how many milliseconds have passed 
	 * since last frame.
	 * 
	 * @return milliseconds passed since last frame 
	 */
	public int getDelta() {
	    long time = getTime();
	    int delta = (int) (time - lastFrame);
	    lastFrame = time;
	 
	    return delta;
	}
	
	/**
	 * Get the accurate system time
	 * 
	 * @return The system time in milliseconds
	 */
	public long getTime() {
	    return (Sys.getTime() * 1000) / Sys.getTimerResolution();
	}
        
        
        
        private int loadTexture(String filename, int minFilter, int magFilter, int wrapMode){
            
            InputStream in;
            int texID = glGenTextures();
            try {
                in = new FileInputStream("textures/" + filename + ".png");
                PNGDecoder decoder = new PNGDecoder(in);
                int width = decoder.getWidth();
                int height = decoder.getHeight();
                
                ByteBuffer buffer = BufferUtils.createByteBuffer(4 * width * height);
                decoder.decode(buffer, width * 4, PNGDecoder.Format.RGBA);          
                buffer.flip();
                in.close();
                
                glBindTexture(GL_TEXTURE_2D, texID);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
                
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
                
                glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
                glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

//                             
                if(minFilter == GL_LINEAR_MIPMAP_LINEAR || 
                    minFilter == GL_LINEAR_MIPMAP_NEAREST ||
                     minFilter == GL_NEAREST_MIPMAP_LINEAR ||
                     minFilter == GL_NEAREST_MIPMAP_NEAREST){
                glGenerateMipmap(GL_TEXTURE_2D);}       
                glBindTexture(GL_TEXTURE_2D, 0);
                
            } catch (FileNotFoundException e) {
                System.err.println("Failed to find the texture file: " + filename + ".png");
                
            } catch (IOException ex) {
                System.err.println("Error reading file: " + filename + ".png");
                
            } 
           
            return texID;
        }
}
